package com.bwie.task;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.es.EsProd;
import com.bwie.mapper.TbProdMapper;
import com.bwie.pojo.TbProd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2025/6/30 14:56
 */

@Component
public class SyncProdTask {

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    TbProdMapper tbProdMapper;


    /**
     * @description 每分钟把商品从MySQL同步到ES中
     * @params []
     * @return void
     * @author 军哥
     * @date 2025/6/30 14:57
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void syncProdToEs() {
        System.out.println("开始执行把商品从MySQL同步到ES中任务");

        //--1 检查索引是否存在，如果不存在，创建索引
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(EsProd.class);
        boolean exists = indexOps.exists();
        if(!exists) {
            // 索引不存在，创建索引
            indexOps.create();

            // 创索引的映射
            Document mapping = indexOps.createMapping();
            indexOps.putMapping(mapping);
        }


        //--2 获取MySQL中的商品数据
        Page<TbProd> page = new Page<>(1, 99999);
        Page<TbProd> prodList = tbProdMapper.getProdList(page, null);

        //--3 循环保存商品数据到ES中
        for (TbProd record : prodList.getRecords()) {
            // 需要把表对象转换为ES对象
            EsProd esProd = BeanUtil.toBean(record, EsProd.class);
            elasticsearchRestTemplate.save(esProd);
        }

        System.out.println("把商品从MySQL同步到ES中 任务结束~~~~~~~~~~~~~~~~");
    }

}
